<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>使用WebSocket接收图显测试</title>
</head>
<body>
<table>
    <tr>
        <td>
            <img ref="imageRef" class="remote" src="" alt="" />
        </td>
    </tr>
</table>

<script>
    /**
     * 一、使用WebSocket接收图显测试
     * @type {null}
     */

    // import ReconnectingWebSocket from 'reconnecting-websocket'
    // import { Base64 } from 'js-base64'


    // const route = useRoute()
    let socket = null
    const secretKey = 'keyXXXXXXX'
    const remoteControl = '192.168.1.xxx'
    // const scoketURL = `ws://${remoteControl}:10086/Echo?key=${Base64.encode(secretKey)}`
    const scoketURL = 'ws://124.222.224.186:8800'
    const imageRef = ""
    let timer = null
    const clientWidth = document.documentElement.offsetWidth
    let clientHeight = null
    const widthCss = (window.innerWidth) + 'px'
    const heightCss = (window.innerHeight) + 'px'
    const imgWidth = "" // 图片宽度
    const imgHeight = "" // 图片高度

    const createdWebsocket = () => {
        socket = new WebSocket(scoketURL)
        socket.onopen = function () {
            console.log('连接已建立')
            resetHeart()
            setTimeout(() => {
                watchControl()
            }, 500)
        }
        socket.onmessage = function (event) {
            if (event.data instanceof Blob) { // 处理桌面流
                const data = event.data
                const blob = new Blob([data], { type: 'image/jpg' })
                imageRef.value.src = window.URL.createObjectURL(blob)
            } else {
                const objectDta = JSON.parse(event.data)
                console.log(objectDta)
                if (objectDta.type === 100) {
                    resetHeart()
                }
            }
        }
        socket.onclose = function () {
            console.log('断开连接')
        }
    }

    const handleMousemove = (e) => { // 鼠标移动
        if (!timer) {
            timer = setTimeout(function () {
                const newPageX = parseInt(e.pageX * (imgWidth.value / clientWidth)) // 计算分辨率
                const newPageY = parseInt(e.pageY * (imgHeight.value / clientHeight))
                // console.log(newPageX, 'newPageX')
                // console.log(newPageY, 'newPageY')
                // console.log('鼠标移动:X轴位置' + e.pageX + ';Y轴位置:' + e.pageY)
                socket.send(JSON.stringify({ type: 2, x: newPageX, y: newPageY }))
                timer = null
            }, 60)
        }
    }
    const handleKeydown = (e) => { // 键盘按下
        console.log('键盘按下', e)
        socket.send(JSON.stringify({ type: 0, key: e.keyCode }))
    }
    const handleMousedown = (e) => { // 鼠标单击按下
        console.log('单击按下', e)
        const newPageX = parseInt(e.pageX * (imgWidth.value / clientWidth)) // 计算分辨率
        const newPageY = parseInt(e.pageY * (imgHeight.value / clientHeight))
        console.log(newPageX, 'newPageX')
        console.log(newPageY, 'newPageY')
        socket.send(JSON.stringify({ type: 5, x: newPageX, y: newPageY }))
    }
    const handleKeyup = (e) => { // 键盘抬起
        console.log('键盘抬起', e)
        socket.send(JSON.stringify({ type: 1, key: e.keyCode }))
    }

    const handleMouseup = (e) => { // 鼠标单击抬起
        console.log('单击抬起', e)
        const newPageX = parseInt(e.pageX * (imgWidth.value / clientWidth)) // 计算分辨率
        const newPageY = parseInt(e.pageY * (imgHeight.value / clientHeight))
        console.log(newPageX, 'newPageX')
        console.log(newPageY, 'newPageY')
        socket.send(JSON.stringify({ type: 6, x: newPageX, y: newPageY }))
    }

    const handleContextmenu = (e) => { // 鼠标右击
        console.log('右击', e)
        e.preventDefault()
        const newPageX = parseInt(e.pageX * (imgWidth.value / clientWidth)) // 计算分辨率
        const newPageY = parseInt(e.pageY * (imgHeight.value / clientHeight))
        console.log(newPageX, 'newPageX')
        console.log(newPageY, 'newPageY')
        socket.send(JSON.stringify({ type: 4, x: newPageX, y: newPageY }))
    }

    const handleDblclick = (e) => { // 鼠标双击
        console.log('双击', e)
    }

    const handleMousewheel = (e) => { // 鼠标滚动
        console.log('滚动', e)
        const moving = e.deltaY / e.wheelDeltaY
        socket.send(JSON.stringify({ type: 7, x: e.x, y: e.y, deltaY: e.deltaY, deltaFactor: moving }))
    }

    const watchControl = () => { // 监听事件
        console.dir(imageRef.value)
        imgWidth.value = imageRef.value.naturalWidth === 0 ? 1920 : imageRef.value.naturalWidth// 图片宽度
        imgHeight.value = imageRef.value.naturalHeight === 0 ? 1080 : imageRef.value.naturalHeight // 图片高度
        clientHeight = document.body.offsetHeight

        window.ondragstart = function (e) { // 移除拖动事件
            e.preventDefault()
        }
        window.ondragend = function (e) { // 移除拖动事件
            e.preventDefault()
        }
        window.addEventListener('mousemove', handleMousemove)
        window.addEventListener('keydown', handleKeydown)
        window.addEventListener('mousedown', handleMousedown)
        window.addEventListener('keyup', handleKeyup)
        window.addEventListener('mouseup', handleMouseup)
        window.addEventListener('contextmenu', handleContextmenu)
        window.addEventListener('dblclick', handleDblclick)
        window.addEventListener('mousewheel', handleMousewheel)
    }

    let heartTime = null // 心跳定时器实例
    let socketHeart = 0 // 心跳次数
    const HeartTimeOut = 20000 // 心跳超时时间
    let socketError = 0 // 错误次数
    // socket 重置心跳
    const resetHeart = () => {
        socketHeart = 0
        socketError = 0
        clearInterval(heartTime)
        sendSocketHeart()
    }
    const sendSocketHeart = () => {
        heartTime = setInterval(() => {
            if (socketHeart <= 3) {
                console.log('心跳发送：', socketHeart)
                socket.send(
                    JSON.stringify({
                        type: 100,
                        key: 'ping'
                    })
                )
                socketHeart = socketHeart + 1
            } else {
                reconnect()
            }
        }, HeartTimeOut)
    }
    // socket重连
    const reconnect = () => {
        socket.close()
        if (socketError <= 3) {
            clearInterval(heartTime)
            socketError = socketError + 1
            console.log('socket重连', socketError)
        } else {
            console.log('重试次数已用完的逻辑', socketError)
            clearInterval(heartTime)
        }
    }

    const socketClose = () => {
        socket.close()
        console.log('组件销毁')
        window.removeEventListener('mousemove', handleMousemove)
        window.removeEventListener('keydown', handleKeydown)
        window.removeEventListener('mousedown', handleMousedown)
        window.removeEventListener('keyup', handleKeyup)
        window.removeEventListener('mouseup', handleMouseup)
        window.removeEventListener('contextmenu', handleContextmenu)
        window.removeEventListener('dblclick', handleDblclick)
        window.removeEventListener('mousewheel', handleMousewheel)
    }

    createdWebsocket()
</script>


<script>
    /**
     * 二、测试WebSocket连接
     */
    function testWebSocket() {
        // 创建WebSocket连接
        const socket = new WebSocket('ws://your-server-address');

        // 当WebSocket打开时，发送视频流数据
        socket.addEventListener('open', function (event) {
            // 假设你有一个视频标签<video id="video" src="your-video-source.mp4"></video>
            // 并且你想要发送视频的二进制数据
            const video = document.getElementById('video');
            const mediaRecorder = new MediaRecorder(video.captureStream(), {mimeType: 'video/webm'});

            mediaRecorder.ondataavailable = function (event) {
                if (socket.readyState === WebSocket.OPEN) {
                    // 发送视频片段
                    socket.send(event.data);
                    console.log(event.data);
                }
            };

            mediaRecorder.start();
            //说明：开始录制，timeslice 为可选参数，如果设置了则会按时间切片存储数据。单位秒 s
            //mediaRecorder.start(timeslice);
        });

        // 接收服务器响应或者其他客户端消息
        socket.addEventListener('message', function (event) {
            console.log('Received data from server:', event.data);
        });

        // 处理错误情况
        socket.addEventListener('error', function (event) {
            console.error('WebSocket error observed:', event);
        });
    }
</script>

<style scoped>
    .remote {
        width: v-bind(widthCss);
        height: v-bind(heightCss);
    }
</style>

</body>
</html>